import axios from "axios";
import fetchJsonp from "fetch-jsonp";

const http = (url: string, method: "POST" | "GET", data: any, headers = {}) => {
	const tempData = method == "GET" ? { params: data } : { data };
	console.log(headers);
	return axios({
		url: process.env.NODE_ENV === "development" ? "/api" + url : url,
		method,
		...tempData,
		headers,
	})
		.then((res) => {
			if (res.data.success !== true) {
				throw res.data.errorMsg || "NETWORK ERROR";
			}
			if (url.includes("queryFormConfiguration")) {
				// debugger;
			}
			return res.data;
		})
		.catch((err) => {
			throw "NETWORK ERROR";
		});
};

export default http;

export const httpJsonp = (url: string, params: Record<string, string | number>) => {
	const tempParams = Object.entries(params)
		.reduce((res, next) => {
			return `${res}&${next[0]}=${encodeURIComponent(next[1])}`;
		}, "")
		.slice(1);

	return fetchJsonp(url + "?" + tempParams).then((res) => res.json());
};
